<?php
namespace Api\Xml;

use Api\Xml\Schema\Exception\XmlSchemaException;

/**
 * Class Schema
 * @package Api\Xml
 */
class Schema
{
    protected $xmlSchemaFile;

    /**
     * @var \DOMDocument
     */
    public $dom;

    /**
     * Constructor
     *
     * @param $xmlSchemaFile
     */
    public function __construct($xmlSchemaFile)
    {
        libxml_use_internal_errors(true);

        $this->xmlSchemaFile = $xmlSchemaFile;

        $xml = new \DOMDocument('1.0', 'UTF-8');
        $xml->preserveWhiteSpace = false;
        $xml->formatOutput = true;
        $xml->encoding = 'UTF-8';

        $this->dom = $xml;
    }

    /**
     * Validate
     *
     * @param $xml
     * @return \DOMDocument
     * @throws Schema\Exception\XmlSchemaException
     */
    public function validate($xml)
    {
        $this->dom->loadXML($xml);

        if (!$this->dom->schemaValidate($this->xmlSchemaFile))
        {
            $errors = (array)libxml_get_errors();

            throw new XmlSchemaException($errors);
        }

        return $this->dom;
    }
}